// pages/edit/edit.js
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _id: '',
    cover: '',
    name: '',
    url: '',
    category_id: '',
    parent_id: '',
    sort: 0,
    password: '',
    categories: [],
    categoryIndex: -1,
    arrCategories: []
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCategories(options);
  },
  getBookById: function (_id) {
    let that = this;
    db.collection("books").doc(_id).get({
      success: function (res) {
        var bookData = res.data;
        //设置categoryIndex
        var categoryIndex = -1;
        for (var i = 0; i < that.data.categories.length; i++) {
          if (that.data.categories[i]._id == bookData.category_id) {
            categoryIndex = i;
            break;
          }
        }
        console.log(categoryIndex);
        that.setData({
          _id: res.data._id,
          sort: res.data.sort,
          cover: res.data.cover,
          name: res.data.name,
          url: res.data.url,
          category_id: res.data.category_id,
          parent_id: res.data.parent_id,
          password: res.data.password == undefined ? '' : res.data.password,
          categoryIndex: categoryIndex
        });
      }
    });
  },
  bindCategoryChange: function (e) {
    this.setData({
      categoryIndex: e.detail.value
    })
  },
  getCategories: function (options) {
    let that = this;
    db.collection('categories').where({
        public: true
      })
      .get({
        success: function (res) {
          // res.data 是包含以上定义的两条记录的数组
          let arrCategories = [];
          let categories = res.data;
          for (let i = 0; i < categories.length; i++) {
            arrCategories.push(categories[i].name);
          }
          that.setData({
            arrCategories: arrCategories,
            categories: categories
          });
          if (options._id) {
            that.getBookById(options._id);
          }
        }
      })
  },
  bindPwdInput: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  bindTitleInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindUrlInput: function (e) {
    this.setData({
      url: e.detail.value
    })
  },
  goHome: function () {
    setTimeout(() => {
      getCurrentPages()[0].getBookList();
      wx.navigateBack({
        delta: 2,
      })
    }, 2000);
  },
  del: function () {
    let that = this;
    if (that.data._id) {
      db.collection('books').doc(that.data._id).remove({
        success: function (res) {
          wx.showToast({
            title: '删除成功'
          })
          //刷新首页并返回
          that.goHome();
        }
      })
    } else {
      wx.showToast({
        title: '没有id'
      })
    }
  },
  save: function () {
    let that = this;
    let book = {
      name: that.data.name,
      cover: that.data.cover,
      sort: that.data.sort,
      url: that.data.url,
      parent_id: '',
      category_id: that.data.categories[that.data.categoryIndex]._id,
      password: that.data.password
    };

    if (!that.data._id) {
      db.collection('books').add({
        // data 字段表示需新增的 JSON 数据
        data: book,
        success: function (res) {
          // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
          wx.showToast({
            title: '添加成功'
          })
          that.goHome();
        },
        fail: function (e) {
          wx.showToast({
            title: '添加失败'
          })
        }
      })
    } else {
      //修改
      db.collection('books').doc(that.data._id).update({
        // data 传入需要局部更新的数据
        data: book,
        success: function (res) {
          wx.showToast({
            title: '修改成功'
          })
          that.goHome();
        }
      })
    }
  },
  doUpload: function () {
    let that = this;
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]

        // 上传图片
        const cloudPath = `my-image-${(new Date()).getTime()}-${filePath.match(/\.[^.]+?$/)[0]}`
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            that.setData({
              cover: res.fileID
            });
            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      },
      fail: e => {
        console.error(e)
      }
    })
  }
})